package com.songlanyun.modules.goods.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.enums.HouniaoConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.supplychainapi.goods.model.GoodsDetailResult;
import com.songlanyun.common.utils.*;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.common.validator.group.AddGroup;
import com.songlanyun.common.validator.group.UpdateGroup;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.entity.UserShopRoleEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserShopRoleService;
import com.songlanyun.modules.category.entity.SystemProductCategoryEntity;
import com.songlanyun.modules.category.service.SystemProductCategoryService;
import com.songlanyun.modules.exception.GoodsExceptionEnum;
import com.songlanyun.modules.freighttemplate.entity.FreightTemplate;
import com.songlanyun.modules.freighttemplate.service.FreightTemplateService;
import com.songlanyun.modules.goods.config.GoodsCategoryConfig;
import com.songlanyun.modules.goods.dao.GoodsDao;
import com.songlanyun.modules.goods.entity.*;
import com.songlanyun.modules.goods.model.dto.*;
import com.songlanyun.modules.goods.model.values.GoodsSkuTableItem;
import com.songlanyun.modules.goods.model.values.SkuItem;
import com.songlanyun.modules.goods.model.values.SkuSet;
import com.songlanyun.modules.goods.model.vo.GoodsPageReq;
import com.songlanyun.modules.goods.model.vo.GoodsSlimVo;
import com.songlanyun.modules.goods.service.*;
import com.songlanyun.modules.goodsuserdiscount.entity.GoodsUserDiscountConfig;
import com.songlanyun.modules.goodsuserdiscount.entity.GoodsUserDiscountDetail;
import com.songlanyun.modules.group.entity.ProductGoodsGroupEntity;
import com.songlanyun.modules.group.service.ProductGoodsGroupService;
import com.songlanyun.modules.hxcategory.entity.HxCategoryEntity;
import com.songlanyun.modules.hxcategory.service.HxCategoryEntityService;
import com.songlanyun.modules.keywordsearch.service.SystemKeyWordSearchService;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.entity.ShopUserRoleConfigEntity;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.shop.service.ShopUserRoleConfigService;
import com.songlanyun.modules.singlegoods.entity.ProductSingleGoodsEntity;
import com.songlanyun.modules.singlegoods.service.ProductSingleGoodsService;
import com.songlanyun.modules.skus.entity.ProductSkusEntity;
import com.songlanyun.modules.skus.service.ProductSkusService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {

    @Value("${goodsPriceMultiplier}")
    private String goodsPriceMultiplier;
    @Autowired
    private GoodsGroupRelationService goodsGroupRelationService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private GoodsAuthShopService goodsAuthShopService;
    @Autowired
    private GoodsContentService goodsContentService;
    @Autowired
    private SystemProductCategoryService SystemProductCategoryService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private ProductSingleGoodsService singleGoodsService;

    @Autowired
    private ProductGoodsGroupService productGoodsGroupService;

    @Autowired
    private SystemProductCategoryService systemProductCategoryService;

    @Autowired
    private HxCategoryEntityService hxCategoryEntityService;


    //这个是商家会员的等级的配置
    @Autowired
    private ShopUserRoleConfigService shopUserRoleConfigService;

    @Autowired
    private UserShopRoleService userShopRoleService;


    @Autowired
    private FreightTemplateService freightTemplateService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private SystemKeyWordSearchService systemKeyWordSearchService;

    @Autowired
    private ProductSkusService skuService;


    @Autowired
    private ProductSingleGoodsService productSingleGoodsService;


    @Autowired
    private HouniaoApiUtil houniaoApiUtil;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ProductSkusService productSkusService;

    @Autowired
    private GoodsDao goodsDao;


    /**
     * 创建商品
     *
     * @param entity
     * @return
     */
    @Override
    public Goods create(Goods entity) {

        ValidatorUtils.validateEntity(entity, AddGroup.class);
        this.baseMapper.insert(entity);
        return entity;
    }


    /**
     * 作改商品
     *
     * @param entity
     * @return
     */
    @Override
    public Goods modify(Goods entity) {
        ValidatorUtils.validateEntity(entity, UpdateGroup.class);
        this.baseMapper.updateById(entity);
        return this.getById(entity.getId());
    }

    /**
     * 移除商品
     *
     * @param id
     * @return
     */
    @Override
    public void remove(Long id) {
        this.removeById(id);
    }

    @Override
    @Transactional
    public void delete(Long shopId, Long id) {
        shopService.loadShopBy(shopId, true);
        Goods entity = validateExists(id);
        validateGoodsShopSafe(shopId, entity);
        GoodsStatusDTO dto = new GoodsStatusDTO();
        dto.setGoodsId(entity.getId());
        dto.setAdded(false);
        goodsAuthShopService.added(shopId, dto);
        //goodsSkuService.clearByGoodsId(entity.getId());
        this.remove(id);
    }

    @Override
    public void updateAverageById(Long goodsId, BigDecimal average) {
        this.update(
                new LambdaUpdateWrapper<Goods>()
                        .eq(Goods::getId, goodsId)
                        .set(Goods::getAverage, average)
        );
    }

    @Override
    public void setProxy(Long shopId, GoodsStatusDTO dto) {
        ShopEntity shopEntity = shopService.loadShopBy(shopId, true);
        if (!shopEntity.getPlatformShop()) {
            throw new RRException(GoodsExceptionEnum.PLATFORM_SHOP_ABLE_PROXY);

        }
        Goods entity = this.validateExists(dto.getGoodsId());
        validateGoodsShopSafe(shopId, entity);
        if (entity.getPointGoods()) {//积分商品不能代销
          throw new RRException(GoodsExceptionEnum.POINT_GOODS_NOT_PROXY);
        }
        entity.setAbleProxySale(dto.getAbleProxySale());
//        entity.setGiftType(GoodsConstant.GiftType.getByCode(dto.getGiftType()));
        entity.setGiftType(GoodsConstant.GiftType.COMMON);
        this.modify(entity);


        /**
         * 如果取消代销之后，所有之前代销经营权限删除
         */
        if (!entity.getAbleProxySale()) {
            goodsAuthShopService.removeCommonShopAuth(shopId, dto.getGoodsId());

        }

    }

    /**
     * 只从店铺筛选商品
     *
     * @param params
     * @return
     */
    @Override
    public List<GoodsSlimVo> loadList(Map<String, Object> params) {
        return this.baseMapper.loadList(paramsMapToReq(params));
    }

    /**
     * 从全平台筛选新上加商品
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils newAddedGoodsList(Map<String, Object> params) {
        GoodsPageReq goodsPageReq = paramsMapToReq(params);
        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.newAddedGoodsList(new Query<GoodsSlimVo>().getPage(params), goodsPageReq);
        return new PageUtils(goodsSlimVoIPage);
    }

    @Override
    public Integer saleGoodsNum(Long startTime, Long endTime) {
        return this.baseMapper.saleGoodsNum(startTime, endTime);
    }

    @Override
    public List<GoodsSlimVo> saleGoodsListByTime(Long startTime, Long endTime, Integer limit) {
        return this.baseMapper.saleGoodsListByTime(startTime, endTime, limit);
    }

    @Override
    public List<GoodsSlimVo> saleGoodsList(Integer limit) {
        return this.baseMapper.saleGoodsList(limit);
    }

    /**
     * 月销量商品列表
     *
     * @param limit
     * @param mixNum
     * @return
     */
    @Override
    public List<GoodsSlimVo> monthSaleGoodsList(Integer limit, Integer mixNum) {
        DateTime startTime = DateUtil.beginOfMonth(new Date());
        DateTime endTime = DateUtil.endOfMonth(new Date());
        Integer num = this.saleGoodsNum(startTime.getTime(), endTime.getTime());
        if (num < mixNum) {
            return this.saleGoodsList(limit);
        } else {
            return this.saleGoodsListByTime(startTime.getTime(), endTime.getTime(), limit);
        }
    }


    /**
     * 设置是否开始会员折扣
     *
     * @param shopId
     * @param dto
     */
    @Override
    public void openUserDiscount(Long shopId, GoodsStatusDTO dto) {
        Goods entity = this.getByShopIdAndId(shopId, dto.getGoodsId());
        entity.setOpenUserDiscount(dto.getOpenUserDiscount());
        this.modify(entity);
    }

    @Override
    public int countByTemplate(Integer templateId) {
        return this.baseMapper.selectCount(new LambdaQueryWrapper<Goods>().eq(Goods::getFreightTemplateId, templateId));
    }

    @Override
    public Integer loadCount(Map<String, Object> params) {
        return this.baseMapper.loadCount(paramsMapToReq(params));
    }

    /**
     * 积分商品列表
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils pointGoodsGage(Map<String, Object> params) {

        GoodsPageReq goodsPageReq = paramsMapToReq(params);
        goodsPageReq.setVerifyStatus(1);
        goodsPageReq.setAdded(1);
        goodsPageReq.setPointGoods(1);

        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.pointGoodsGage(new Query<GoodsSlimVo>().getPage(params), goodsPageReq);
        return new PageUtils(goodsSlimVoIPage);

    }

    /**
     * 免费领商品
     * @param params
     * @return
     */
    @Override
    public PageUtils freeGoodsGage(Map<String, Object> params) {
        GoodsPageReq goodsPageReq = paramsMapToReq(params);
        goodsPageReq.setVerifyStatus(1);
        goodsPageReq.setAdded(1);
        goodsPageReq.setPointGoods(1);

        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.freeGoodsGage(new Query<GoodsSlimVo>().getPage(params), goodsPageReq);
        return new PageUtils(goodsSlimVoIPage);
    }

    /**
     * 猜你喜欢
     *
     * @param params
     * @return
     */
    @Override
    public List<GoodsSlimVo> smartRecommend(Map<String, Object> params) {
        List<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.smartRecommend(paramsMapToReq(params));
        if(goodsSlimVoIPage != null){
            // 过滤掉售价为零和库存为零的商品
            goodsSlimVoIPage = goodsSlimVoIPage.stream().filter(g -> {
                g.loadResidualInventory();
                return (g.getMinSalePrice().compareTo(BigDecimal.ZERO) > 0 && g.getResidualInventory() > 0);
            }).collect(Collectors.toList());
        }
        return goodsSlimVoIPage;

    }

    @Override
    public Integer goodsStatistics(Long shopId, Integer added) {
        return this.baseMapper.goodsStatistics(shopId, added);
    }

    @Override
    public Integer rarelyGoodsNum(Long shopId) {
        Integer num = 10;//商品库存<=10件的，为库存紧张的商品
        return singleGoodsService.rarelyGoodsNum(shopId, num);
    }

    @Override
    public PageUtils randRecommend(Map<String, Object> params) {
        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.randRecommend(new Query<GoodsSlimVo>().getPage(params), paramsMapToReq(params));
        return new PageUtils(goodsSlimVoIPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pullThirdGoods(PullChainGoodsDto dto) {
        Integer num = getThirdNum(dto.getShopId(),dto.getThirdSpuId());
        if(num > 0)
        {
            throw new RRException("当前这个商品已下拉过，不要重复下拉");
        }

        GoodsDTO goodsDTO = new GoodsDTO();
        mapToGoodsBaseInfo(goodsDTO,dto);
        mapToSkuTable(goodsDTO,dto);
        mapToGoodsSkuList(goodsDTO,dto);
        this.add(dto.getShopId(), goodsDTO);
    }

    @Override
    public Integer getThirdNum(Long shopId,Long thirdSpuId) {
        return this.baseMapper.selectCount(new LambdaQueryWrapper<Goods>()
                    .eq(Goods::getShopId, shopId)
                    .eq(Goods::getThird, 1)
                    .eq(Goods::getThirdSpuId, thirdSpuId)
                    .last("limit 1"));
    }

    @Override
    public Goods loadByThirdSpuId(Long thirdSpuId) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getThird, 1)
                .eq(Goods::getThirdSpuId, thirdSpuId)
                .last("limit 1"));
    }

    @Override
    public List<GoodsSlimVo> queryRecommend(List<Long> goodsIds) {
        return this.baseMapper.queryRecommend(goodsIds);
    }

    @Override
    public void addHouniaoGoods(Integer currentPage, String tradeTypeId) {
        for (int h = currentPage; h < 2671; h++) {
            JSONObject req = new JSONObject();
            if (tradeTypeId != null && !"".equals(tradeTypeId)) {
                req.put("trade_type_id", tradeTypeId);
            }
            req.put("current_page", h);
            req.put("page_size", 50);
            req.put("offset", 0);
            JSONObject js = new JSONObject();
            try {
                js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_GET_LIST.getUrl());
            } catch (Exception e) {
                if (!js.get("code").toString().equals(200)) {
                    throw new RRException("商品添加异常");
                }
            }
            //获取数据
            JSONObject data = js.getJSONObject("data");
            //获取商品集合
            JSONArray data1 = data.getJSONArray("data");

            int size1 = data1.size();

            //候鸟商品集合
            List<Goods> houNiaoGoodsList = new ArrayList<>();
            //goodSpu字符串拼接
            String goodsSpus = "";

            JSONArray jsonArray = new JSONArray();
            JSONObject xiangqingjs = new JSONObject();
            for (int i = 0; i < size1; i++) {
                JSONObject jsonObject = data1.getJSONObject(i);
                Goods good = new Goods();
                try {
                    //做非空判断
                    good = goodsService.getByGoodsSpu(jsonObject.get("goods_spu").toString());
                } catch (Exception e) {
                    goodsService.remove(new LambdaQueryWrapper<Goods>()
                            .eq(Goods::getSpuCode, jsonObject.get("goods_spu").toString()));
                    continue;
                }
                if (good == null) {
                    // 获取商品列表中的spu
                    goodsSpus = goodsSpus + jsonObject.get("goods_spu").toString() + ",";
                }
            }
            if (!goodsSpus.equals("") && goodsSpus != null) {
                goodsSpus = goodsSpus.substring(0, goodsSpus.length() - 1);
            } else {
                continue;
            }
            // 获取商品的详情
            JSONObject xiangqing = new JSONObject();
            xiangqing.put("goods_spu", goodsSpus);
            xiangqing.put("page_size", 50);
            try {
                xiangqingjs = houniaoApiUtil.client(xiangqing, HouniaoConstant.GOODS_GET_LIST.getUrl());
            } catch (Exception e) {
                continue;
            }
            /**
             * **************调用存储商品表的方法***************
             */
            goodsAddss(xiangqingjs);
        }
    }

    /**
     * 单个商品新增
     * 实现列表新增需要循环调用
     */
    public List<Goods> goodsAddss(JSONObject xiangqingjs) {

        JSONObject datas = xiangqingjs.getJSONObject("data");
        //商品详情集合
        JSONArray goodArrays = datas.getJSONArray("data");

        Goods goods = null;

        List<Goods> goodsList = new ArrayList<>();
        for (int i = 0; i < goodArrays.size(); i++) {

            JSONObject data = goodArrays.getJSONObject(i);
            //获取商品规格
            JSONObject req1 = new JSONObject();
            req1.put("goods_spu", data.get("goods_spu").toString());
            JSONObject json = new JSONObject();
            try {
                json = houniaoApiUtil.client(req1, HouniaoConstant.GOODS_GET_GOODS_SPEC_PRICE_BATCH.getUrl());
            } catch (Exception e) {
                goodArrays.remove(i);
                continue;
            }
            JSONArray data3 = json.getJSONArray("data");
            JSONObject jsonObject1 = data3.getJSONObject(0);
            JSONArray sku_list = jsonObject1.getJSONArray("sku_list");
            //商品如果没有规格 不添加该商品
            if (sku_list.size() == 0) {
                continue;
            }


            goods = new Goods();
            //贸易类型id，1=保税直供，2=完税进口，3=国内贸易，4=香港直邮，5=海外直邮
            goods.setTradeTypeId(Integer.valueOf(data.get("trade_type_id").toString()));
            //shopId 30为候鸟
            goods.setShopId(35L);
            goods.setRealSaleNum(Integer.valueOf(data.get("sale_num").toString()));
            goods.setCover(data.getJSONObject("goods_img").get("img").toString());
            //分类id TODO: 存商品前，分好商品类  根据商品的spu去商品详情查
            //获取category_id_path 做判断
            String category_id_path = data.get("category_id_path").toString();
            try {
                //获取category_id_path的前两位
                category_id_path = category_id_path.substring(0, category_id_path.lastIndexOf("_"));
                //goods.setCategoryId(getCategoryId(category_id_path));
                Long categoryId = GoodsCategoryConfig.getGoodsCategoryMap().get(category_id_path);
                goods.setCategoryId(categoryId);
            } catch (Exception exception) {
                goods.setCategoryId(0L);
            }

            /**
             * 商品价格倍率
             */
            //商品价格
            BigDecimal min_price = new BigDecimal(data.get("min_price").toString());
            //候鸟商品价格倍率
            BigDecimal goodsPriceMultiplier = new BigDecimal(HouniaoConstant.GOODS_PRICE_MULTIPLIER.getUrl());
            //最终价格
            BigDecimal result = min_price.multiply(goodsPriceMultiplier);
            goods.setMinSalePrice(result);
            goods.setMaxSalePrice(result);
            goods.setMinMarketPrice(result);
            goods.setMaxMarketPrice(result);
//        goods.setMinSalePrice(new BigDecimal(data.get("min_price").toString()));
//        goods.setMaxSalePrice(new BigDecimal(data.get("min_price").toString()));
//        goods.setMinMarketPrice(new BigDecimal(data.get("min_price").toString()));
//        goods.setMaxMarketPrice(new BigDecimal(data.get("min_price").toString()));
            goods.setMinExchangePoint(new BigDecimal(0.00));
            goods.setTitle(data.get("goods_name").toString());
            goods.setVideoUrl("");
            goods.setShortTitle("");
            goods.setSpuCode(data.get("goods_spu").toString());
            //商品规格 添加商品时设置为null  添加商品规格时 更新字段
            goods.setGoodsSkuList(new ArrayList<>());
            goods.setInitSaleNum(0);
            goods.setLimitBuyNum(0);
            //实际出售量
            goods.setRealSaleNum(Integer.valueOf(data.get("sale_num").toString()));
            goods.setResultSaleNum(Integer.valueOf(data.get("sale_num").toString()));
            //是否是积分兑换
            goods.setPointGoods(false);
            //浏览量
            goods.setPv(0L);
            goods.setVerifyStatus(GoodsConstant.VerifyStatus.YES);
            //顺序暂时为0 不知道干什么用的
            goods.setSort(Integer.valueOf(0));
            //是否是平台商品  暂时设置为不是
            goods.setPlatformStore(false);
            //运费模版 暂时写死
            goods.setFreightTemplateId(6);
            //最后审核时间  暂时设置为导入时间
            goods.setLastVerifyTime(new Date());
            //软删除  0正常 -1删除
            goods.setDeleted(0);
            //是否开启会员折扣  暂时为false 不知道具体用途
            goods.setOpenUserDiscount(false);
            //暂时设置为热销
            goods.setHot(false);
            //是否是新品  暂时设置为不是
            goods.setNewGoods(false);
            //是否推荐 暂时设置为是
            goods.setRecommend(true);
            goods.setAverage(new BigDecimal(5.0));
            //是否可以代理销售暂时设置为false
            goods.setAbleProxySale(false);
            goods.setGiftType(GoodsConstant.GiftType.NO);
            //赠送积分暂时设置为0
            goods.setGivePoint(new BigDecimal(0));
            //赠送消费值 暂时写死 不知道计算原理
            goods.setConsumptionValue(goods.getMinSalePrice());
            goods.setFree(false);
            //是否是激活商品  暂时设置为是
            goods.setAreaFeature(GoodsConstant.AreaFeature.GENERAL);
            //三方的spuid暂时写死
            goods.setHouniaoSpuId(goods.getSpuCode());
            //是否是三方产品 暂时设置为是
            goods.setThird(true);
            //sorce  暂时给99
            goods.setSource(99);
            //规格
            goods.setSkuTable(new ArrayList());
            goodsList.add(goods);
        }
        // 追加到商品详情list
        if (goodsList != null) {
            goodsService.saveBatch(goodsList);
            //商品详情和库存保存
            goodsDetailsAndInventoryPreservation(goodsList, goodArrays);
        }
        return goodsList;
    }

    //商品详情和库存保存
    public void goodsDetailsAndInventoryPreservation(List<Goods> goodsList, JSONArray jsonArray){
        List<GoodsContent> goodsContentList = new ArrayList<>();
        List<ProductSingleGoodsEntity> productSingleGoodsEntityList = new ArrayList<>();
        List<GoodsAuthShop> goodsAuthShopList = new ArrayList<>();
        List<Goods> goodsUpdateList = new ArrayList<>();

        a:for (int i = 0; i < goodsList.size(); i++) {
            Goods good = goodsList.get(i);
            JSONObject xiangqingjs = jsonArray.getJSONObject(i);
            // 遍历返回的"goods_desc_image"
            JSONObject data = xiangqingjs;
            JSONArray goods_desc_image = data.getJSONArray("goods_desc_image");
            StringBuilder goods_desc_image_url = new StringBuilder();
            String qian = "<img src=\"";
            // 遍历图片
            goods_desc_image.forEach(item -> {
                goods_desc_image_url.append(qian);
                goods_desc_image_url.append(item.toString());
                goods_desc_image_url.append("\">");
            });
            // StringBuilder -> String
            String goods_desc_image_urls = goods_desc_image_url.toString();
            String zuizhong = "<p>" + goods_desc_image_urls + "</p>";
            GoodsContent goodsContent = new GoodsContent();
            goodsContent.setGoodsId(good.getId());
            goodsContent.setMobileDetail(zuizhong);
            goodsContentList.add(goodsContent);
            //商家的单品表，用来管理库存  //TODO:库存批量导入
            ProductSingleGoodsEntity ps = new ProductSingleGoodsEntity();
            ps.setGoodsGroupId(69L);
            ps.setGoodsGroupName("999");
            ps.setCode(good.getSpuCode());
            ps.setTitle(good.getTitle());
            ps.setCoverImage(good.getCover());
            ps.setUnit(data.get("unit_name").toString());
            ps.setCostPrice(good.getMinSalePrice());
            ps.setOrderIndex(0);
            ps.setAbleStock(999999);
            ps.setDeleted(0);
            ps.setShopId(35L);
            ps.setSku(data.get("unit_name").toString());
            ps.setAdded(true);
            productSingleGoodsEntityList.add(ps);
            //TODO:批量插入单品表 库存管理
            productSingleGoodsService.saveBatch(productSingleGoodsEntityList);
            // 商家所发商品的与店铺的授权关系表，平台店铺发的商品如A,平台会有一条店铺与商品的关系，商家店铺SS也要代销平台商品，则需要建立一条商品A也商品店铺SS的关系，店铺SS可以随时上下架这个平台商品
            GoodsAuthShop shop = new GoodsAuthShop();
            //商品id
            shop.setGoodsId(good.getId());
            //是否上架
            shop.setAdded(true);
            //上架时间
            shop.setCreateTime(new Date());
            //上架状态时间
            shop.setAddedStatusTime(new Date());
            //更新时间
            shop.setUpdateTime(new Date());
            //商家授权id
            shop.setAuthorizeShopId(35L);
            //发表商家店铺
            shop.setPublishShopId(35L);
            goodsAuthShopList.add(shop);

            //获取商品规格
            JSONObject req1 = new JSONObject();
            req1.put("goods_spu",good.getSpuCode());
            JSONObject json = new JSONObject();
            try {
                 json = houniaoApiUtil.client(req1, HouniaoConstant.GOODS_GET_GOODS_SPEC_PRICE_BATCH.getUrl());
            }catch (Exception e){
                continue;
            }
            JSONArray data3 = json.getJSONArray("data");
            JSONObject jsonObject1 = data3.getJSONObject(0);
            JSONArray sku_list = jsonObject1.getJSONArray("sku_list");
            //商品如果没有规格 不添加该商品
            if(sku_list.size() == 0){
                continue;
            }
            //准备一个goods表的拼接字符串
            StringBuilder sb = new StringBuilder();
            int size = sku_list.size();
            //规格集合
            List<GoodsSku> skuList = new ArrayList<>();
            for (int j = 0;j < size; j++){
                JSONObject jsonObject2 = JSON.parseObject(JSONObject.toJSONString(sku_list.get(j)));
                String sku_name = jsonObject2.getString("sku_name");
                // skus表新增
                ProductSkusEntity skusEntity = new ProductSkusEntity();
                skusEntity.setName(sku_name);
                skusEntity.setShopId(35L);
                skusEntity.setParentSkuId(53L);
                skusEntity.setOrderIndex(1);
                productSkusService.save(skusEntity);
                Long skusEntity_id = skusEntity.getId();
                // sku_relation表新增
                //商品的规格的关系表（一个商品可能会有多个规格，各个规格中要关联单品）
                GoodsSku goodsSku = new GoodsSku();
                goodsSku.setGoodsId(good.getId());
                //单品id  不知道怎么用  暂时设置为sku_id  TODO:SingleGoodsId 设为 goodsId
                goodsSku.setSingleGoodsId(ps.getId());
                /**
                 * 无倍率
                 */
//                //暂时设置为规格价格
//                goodsSku.setSalePrice(new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString()));
//                //暂时设置为规格价格
//                goodsSku.setMarketPrice(new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString()));
                /**
                 * 候鸟商品倍率
                 */
                BigDecimal goodsPriceMultiplier = new BigDecimal(HouniaoConstant.GOODS_PRICE_MULTIPLIER.getUrl());
                BigDecimal skuPrice = new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString());
                BigDecimal skuPriceResult = skuPrice.multiply(goodsPriceMultiplier);
                //设置商品的最低价
                if (j == 0){
                    good.setMinSalePrice(skuPriceResult);
                    good.setConsumptionValue(skuPriceResult);
                    good.setMaxMarketPrice(skuPriceResult);
                }
                //实际售价暂时设置为规格价格
                goodsSku.setSalePrice(skuPriceResult);
                //划线价格暂时设置为规格价格
                goodsSku.setMarketPrice(skuPriceResult);

                goodsSku.setWeight(new BigDecimal(sku_list.getJSONObject(j).get("sku_weight").toString()));
                //体积暂时设为0
                goodsSku.setVolume(new BigDecimal(0));
                //规格组合配置的字符串设置 TODO:删除了setSkuSetValue中的方法需要修改
                String str ="[{\"value\": {\"name\": \"" + sku_name + "\",\"id\": \"" + skusEntity_id + "\"}}]";
                String str1 ="{\"name\":\"" + sku_name + "\",\"id\":\"" + skusEntity_id + "\"}";
                try {
                    goodsSku.setSkuSetValue(str);
                }catch (Exception e){
                    continue a;
                }

                //商品规格编码
                goodsSku.setBarCode(sku_list.getJSONObject(j).get("spec_sku").toString());
                //兑换积分暂时设置为0
                goodsSku.setExchangePoint(new BigDecimal(0));
                goodsSku.setCover(sku_list.getJSONObject(j).get("spec_img").toString());
                goodsSku.setSkuSetName(sku_list.getJSONObject(j).getJSONArray("sku_attribute_name").get(0).toString());
                //单品码 暂时设置为spu编码
                goodsSku.setSingleGoodsCode(good.getSpuCode());
                //单品标题
                goodsSku.setSingleGoodsTitle(good.getTitle());
                //sku_hash暂时写死 TODO:skuHashCode 为了快递查找 以后再说先写死  20位随机字符串
                goodsSku.setSkuHashCode(skusEntity_id.toString());
                goodsSku.setShopId(good.getShopId());
                goodsSku.setThirdSkuId(Long.valueOf(sku_list.getJSONObject(j).get("sku_id").toString()));
                goodsSku.setAgreementPrice(new BigDecimal(0.00));
                //三方成本价 写死
                goodsSku.setThirdCostPrice(goodsSku.getSalePrice());
                //指导价 写死
                goodsSku.setGuidePrice(goodsSku.getSalePrice());
                skuList.add(goodsSku);
                // 拼接goods表要的字符串
                sb.append(str1 + ",");
            }
            goodsSkuService.branchCreate(good.getId(),skuList);
            // 最后给goods表的sku_table_value字段拼接好 head块
            // StringBuilder -> String 并且去除最后的逗号
            if (sb.length() > 0){
                String string = sb.substring(0, sb.length() - 1);
                String str1 = "[{\"values\":"+ "[" + string +"],\"head\":{\"name\":\"产品\",\"id\":53}}]";
                try {
                    good.setSkuTableValue(str1);
                }catch(Exception e){
                    continue ;
                }

            }
            JSONObject goods_img = data.getJSONObject("goods_img");
            String img = goods_img.get("img").toString();
            //给商品图片赋值
            String imgValue = "[\"" + img + "\"]";
            try {
                good.setImagesValue(imgValue);
            }catch (Exception e){
                continue;
            }
            good.setGoodsSkuList(skuList);
            goodsUpdateList.add(good);
        }
//        goodsList.forEach(good -> {
//            xiangqing.put("goods_spu", good.getSpuCode());
//            JSONObject xiangqingjs = houniaoApiUtil.client(xiangqing, HouniaoConstant.GOODS_GET_INFO.getUrl());
//            // 遍历返回的"goods_desc_image"
//            JSONObject data = xiangqingjs.getJSONObject("data");
//            JSONArray goods_desc_image = data.getJSONArray("goods_desc_image");
//            StringBuilder goods_desc_image_url = new StringBuilder();
//            String qian = "<img src=\"";
//            // 遍历图片
//            goods_desc_image.forEach(item -> {
//                goods_desc_image_url.append(qian);
//                goods_desc_image_url.append(item.toString());
//                goods_desc_image_url.append("\">");
//            });
//            // StringBuilder -> String
//            String goods_desc_image_urls = goods_desc_image_url.toString();
//            String zuizhong = "<p>" + goods_desc_image_urls + "</p>";
//            GoodsContent goodsContent = new GoodsContent();
//            goodsContent.setGoodsId(good.getId());
//            goodsContent.setMobileDetail(zuizhong);
//            goodsContentList.add(goodsContent);
//            //商家的单品表，用来管理库存  //TODO:库存批量导入
//            ProductSingleGoodsEntity ps = new ProductSingleGoodsEntity();
//            ps.setGoodsGroupId(69L);
//            ps.setGoodsGroupName("999");
//            ps.setCode(good.getSpuCode());
//            ps.setTitle(good.getTitle());
//            ps.setCoverImage(good.getCover());
//            ps.setUnit(data.get("unit_name").toString());
//            ps.setCostPrice(good.getMinSalePrice());
//            ps.setOrderIndex(0);
//            ps.setAbleStock(999999);
//            ps.setDeleted(0);
//            ps.setShopId(30L);
//            ps.setSku(data.get("unit_name").toString());
//            ps.setAdded(true);
//            productSingleGoodsEntityList.add(ps);
//            //TODO:批量插入单品表 库存管理
//            productSingleGoodsService.saveBatch(productSingleGoodsEntityList);
//            // 商家所发商品的与店铺的授权关系表，平台店铺发的商品如A,平台会有一条店铺与商品的关系，商家店铺SS也要代销平台商品，则需要建立一条商品A也商品店铺SS的关系，店铺SS可以随时上下架这个平台商品
//            GoodsAuthShop shop = new GoodsAuthShop();
//            //商品id
//            shop.setGoodsId(good.getId());
//            //是否上架
//            shop.setAdded(true);
//            //上架时间
//            shop.setCreateTime(new Date());
//            //上架状态时间
//            shop.setAddedStatusTime(new Date());
//            //更新时间
//            shop.setUpdateTime(new Date());
//            //商家授权id
//            shop.setAuthorizeShopId(30L);
//            //发表商家店铺
//            shop.setPublishShopId(30L);
//            goodsAuthShopList.add(shop);
//
//            //获取商品规格
//            JSONObject req1 = new JSONObject();
//            req1.put("goods_spu",good.getSpuCode());
//            JSONObject json = houniaoApiUtil.client(req1, HouniaoConstant.GOODS_GET_GOODS_SPEC_PRICE_BATCH.getUrl());
//            JSONArray data3 = json.getJSONArray("data");
//            JSONObject jsonObject1 = data3.getJSONObject(0);
//            JSONArray sku_list = jsonObject1.getJSONArray("sku_list");
//
//            // 准备一个goods表的拼接字符串
//            StringBuilder sb = new StringBuilder();
//            int size = sku_list.size();
//            //规格集合
//            List<GoodsSku> skuList = new ArrayList<>();
//            for (int j = 0;j < size; j++){
//                JSONObject jsonObject2 = JSON.parseObject(JSONObject.toJSONString(sku_list.get(j)));
//                String sku_name = jsonObject2.getString("sku_name");
//                // skus表新增
//                ProductSkusEntity skusEntity = new ProductSkusEntity();
//                skusEntity.setName(sku_name);
//                skusEntity.setShopId(30L);
//                skusEntity.setParentSkuId(53L);
//                skusEntity.setOrderIndex(1);
//                productSkusService.save(skusEntity);
//                Long skusEntity_id = skusEntity.getId();
//                // sku_relation表新增
//                //商品的规格的关系表（一个商品可能会有多个规格，各个规格中要关联单品）
//                GoodsSku goodsSku = new GoodsSku();
//                goodsSku.setGoodsId(good.getId());
//                //单品id  不知道怎么用  暂时设置为sku_id  TODO:SingleGoodsId 设为 goodsId
//                goodsSku.setSingleGoodsId(ps.getId());
//                //暂时设置为规格价格
//                goodsSku.setSalePrice(new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString()));
//                //暂时设置为规格价格
//                goodsSku.setMarketPrice(new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString()));
//                goodsSku.setWeight(new BigDecimal(sku_list.getJSONObject(j).get("sku_weight").toString()));
//                //体积暂时设为0
//                goodsSku.setVolume(new BigDecimal(0));
//                //规格组合配置的字符串设置 TODO:删除了setSkuSetValue中的方法需要修改
//                String str ="[{\"value\": {\"name\": \"" + sku_name + "\",\"id\": \"" + skusEntity_id + "\"}}]";
//                String str1 ="{\"name\":\"" + sku_name + "\",\"id\":\"" + skusEntity_id + "\"}";
//                goodsSku.setSkuSetValue(str);
//                //商品规格编码
//                goodsSku.setBarCode(sku_list.getJSONObject(j).get("spec_sku").toString());
//                //兑换积分暂时设置为0
//                goodsSku.setExchangePoint(new BigDecimal(0));
//                goodsSku.setCover(sku_list.getJSONObject(j).get("spec_img").toString());
//                goodsSku.setSkuSetName(sku_list.getJSONObject(j).getJSONArray("sku_attribute_name").get(0).toString());
//                //单品码 暂时设置为spu编码
//                goodsSku.setSingleGoodsCode(good.getSpuCode());
//                //单品标题
//                goodsSku.setSingleGoodsTitle(good.getTitle());
//                //sku_hash暂时写死 TODO:skuHashCode 为了快递查找 以后再说先写死  20位随机字符串
//                goodsSku.setSkuHashCode(skusEntity_id.toString());
//                goodsSku.setShopId(good.getShopId());
//                goodsSku.setThirdSkuId(Long.valueOf(sku_list.getJSONObject(j).get("sku_id").toString()));
//                goodsSku.setAgreementPrice(new BigDecimal(0.00));
//                //三方成本价 写死
//                goodsSku.setThirdCostPrice(goodsSku.getSalePrice());
//                //指导价 写死
//                goodsSku.setGuidePrice(goodsSku.getSalePrice());
//                skuList.add(goodsSku);
//                // 拼接goods表要的字符串
//                sb.append(str1 + ",");
//            }
//            goodsSkuService.branchCreate(good.getId(),skuList);
//            // 最后给goods表的sku_table_value字段拼接好 head块
//            // StringBuilder -> String 并且去除最后的逗号
//            if (sb.length() > 0){
//                String string = sb.substring(0, sb.length() - 1);
//                System.out.println(string);
//                String str1 = "[{\"values\":"+ "[" + string +"],\"head\":{\"name\":\"产品\",\"id\":53}}]";
//                System.out.println(str1);
//                String ss = "[{\"values\":[{\"name\":\"保质期:2022年06月;规格:1盒装\",\"id\":\"992\"},{\"name\":\"保质期:2022年06月;规格:2盒装\",\"id\":\"993\"},{\"name\":\"保质期:2022年06月;规格:3盒装\",\"id\":\"994\"},{\"name\":\"保质期:2022年06月;规格:4盒装\",\"id\":\"995\"},{\"name\":\"保质期:2022年06月;规格:6盒装\",\"id\":\"996\"},{\"name\":\"保质期:2022年06月;规格:8盒装\",\"id\":\"997\"}],\"head\":{\"name\":\"产品\",\"id\":53}}]";
//                System.out.println(ss);
//                good.setSkuTableValue(str1);
//            }
//            // 商品表img_value
//            JSONObject goods_img = data.getJSONObject("goods_img");
//            String img = goods_img.get("img").toString();
//            String imgValue = "[\"" + img + "\"]";
//            good.setImagesValue(imgValue);
//            good.setGoodsSkuList(skuList);
//            goodsUpdateList.add(good);
//        });

        if (goodsUpdateList.size() > 0){
            //TODO:批量插入商品详情
            goodsContentService.saveBatch(goodsContentList);
            //TODO:商品批量更新
            goodsService.updateBatchById(goodsUpdateList);
            //TODO:批量插入商家所发商品的与店铺的授权
            goodsAuthShopService.saveBatch(goodsAuthShopList);
        }
    }

    @Override
    public Goods getByGoodsSpu(String goodsSpu) {
        Goods goods = goodsService.getOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getSpuCode, goodsSpu)
                .last("limit 1")
        );
        return goods;
    }

    @Override
    public List<Goods> selectAreaGoods() {

        return goodsDao.selectAreaGoods();
    }

    //候鸟商品分类
    public static Long getCategoryId(String categoryIdPath){

        Goods goods = new Goods();
        switch (categoryIdPath){
            case "1_2":
                goods.setCategoryId(86L);
                break;
            case "1_3":
                goods.setCategoryId(96L);
                break;
            case "1_20":
                goods.setCategoryId(97L);
                break;
            case "1_21":
                goods.setCategoryId(98L);
                break;
            case "1_22":
                goods.setCategoryId(99L);
                break;
            case "1_23":
                goods.setCategoryId(100L);
                break;
            case "1_24":
                goods.setCategoryId(101L);
                break;
            case "1_25":
                goods.setCategoryId(102L);
                break;
            case "1_26":
                goods.setCategoryId(103L);
                break;
            //婴儿工具
            case "1_1389":
                //玩具
            case "1_27":
                //图书
            case "1_1442":
                goods.setCategoryId(104L);
                break;
            case "1_28":
                goods.setCategoryId(105L);
                break;
            case "1_29":
                goods.setCategoryId(106L);
                break;
            case "7_118":
            case "7_1523":
            case "7_1529":
            case "7_1528":
                goods.setCategoryId(115L);
                break;
            case "7_135":
            case "7_133":
            case "10_432":
                goods.setCategoryId(95L);
                break;
            case "7_1530":
            case "7_1526":
            case "7_1527":
            case "10_383":
            case "10_405":
            case "10_424":
                goods.setCategoryId(116L);
                break;
            case "10_417":
                goods.setCategoryId(91L);
                break;
            case "9_283":
                goods.setCategoryId(89L);
                break;
            case "9_295":
            case "9_322":
                goods.setCategoryId(112L);
                break;
            case "9_305":
                goods.setCategoryId(113L);
                break;
            case "9_314":
            case "9_333":
            case "9_341":
                goods.setCategoryId(114L);
                break;
            case "9_339":
            case "9_374":
            case "9_376":
            case "9_378":
            case "9_380":
                goods.setCategoryId(77L);
                break;
            case "9_354":
                goods.setCategoryId(107L);
                break;
            case "9_356":
                goods.setCategoryId(87L);
                break;
            case "9_367":
                goods.setCategoryId(113L);
                break;
            case "9_382":
                goods.setCategoryId(108L);
                break;
            case "8_265":
            case "8_181":
            case "8_220":
            case "8_218":
            case "8_1561":
            case "8_1318":
            case "8_282":
            case "8_208":
                goods.setCategoryId(90L);
                break;
            case "519_520":
                goods.setCategoryId(120L);
                break;
            case "519_529":
            case "519_548":
            case "519_560":
            case "519_567":
            case "519_576":
            case "519_585":
            case "519_595":
            case "519_608":
            case "519_615":
            case "519_625":
            case "519_631":
                goods.setCategoryId(91L);
                break;
            case "519_537":
                goods.setCategoryId(119L);
                break;
            case "11_1409":
                goods.setCategoryId(92L);
                break;
            case "11_434":
            case "11_447":
            case "11_460":
            case "11_481":
            case "11_495":
            case "11_508":
            case "16_1420":
            case "16_1431":
            case "16_17":
            case "16_1321":
            case "16_1335":
            case "16_1336":
            case "16_1340":
            case "16_1343":
            case "16_1345":
            case "830_831":
            case "830_870":
            case "830_900":
            case "830_923":
            case "830_953":
                goods.setCategoryId(82L);
                break;
            case "13_633":
                goods.setCategoryId(93L);
                break;
            case "13_650":
            case "13_659":
            case "13_665":
            case "13_673":
            case "13_680":
            case "13_687":
            case "13_700":
            case "13_705":
            case "13_709":
            case "13_717":
            case "13_718":
            case "13_719":
            case "13_720":
            case "13_721":
            case "13_722":
            case "13_723":
            case "13_724":
                goods.setCategoryId(83L);
                break;
            case "14_772":
            case "14_816":
            case "14_820":
            case "14_829":
            case "14_751":
                goods.setCategoryId(88L);
                break;
            case "14_788":
                goods.setCategoryId(109L);
                break;
            case "14_802":
                goods.setCategoryId(110L);
                break;
            case "14_725":
                goods.setCategoryId(111L);
                break;
            case "19_146":
            case "19_151":
            case "19_164":
            case "19_171":
            case "19_178":
            case "19_179":
            case "19_156":
            case "19_1394":
            case "1055_1436":
            case "1055_1056":
            case "1055_1348":
            case "1055_1104":
            case "1055_1128":
            case "1055_1154":
            case "1055_1157":
            case "1055_1197":
            case "1055_1225":
            case "1055_1227":
            case "1229_1230":
            case "1243_1288":
            case "1243_1291":
            case "1243_1298":
            case "1243_1304":
            case "1243_1244":
            case "1243_1259":
            case "1243_1275":
            case "1243_1293":
            case "1315_1390":
            case "1315_1401":
            case "1315_1316":
                goods.setCategoryId(81L);
                break;
            case "955_1414":
            case "955_1450":
            case "955_956":
            case "955_960":
            case "955_962":
                goods.setCategoryId(80L);
                break;
            case "965_966":
            case "965_975":
            case "965_985":
            case "965_992":
            case "965_1001":
                goods.setCategoryId(91L);
                break;
            case "1004_1026":
            case "1004_1035":
            case "1004_1050":
            case "1004_1053":
            case "1004_1346":
            case "1004_1005":
            case "1004_1017":
            case "1229_1241":
                goods.setCategoryId(78L);
                break;
            case "95_1355":
                goods.setCategoryId(85L);
                break;
        }
        return goods.getCategoryId();
    }

    private GoodsDTO mapToGoodsBaseInfo(GoodsDTO goodsDTO,PullChainGoodsDto dto)
    {
        FreightTemplate template = freightTemplateService.getFreeTemplate(dto.getShopId());
        if(ObjectUtil.isNull(template))
        {
            throw new RRException("必须设置一个免邮的物流模板");
        }
        goodsDTO.setShopId(dto.getShopId());
        goodsDTO.setTitle(dto.getGoodsDetailResult().getTitle());
        goodsDTO.setShortTitle(StrUtil.getNumStr(dto.getGoodsDetailResult().getTitle(),10));
        goodsDTO.setAreaFeature(0);
        goodsDTO.setCategoryId(dto.getCategoryId());
        goodsDTO.setConsumptionValue(dto.getConsumptionValue());
        goodsDTO.setFree(false);
        goodsDTO.setFreightTemplateId(template.getId());
        goodsDTO.setPointGoods(false);
        goodsDTO.setGivePoint(BigDecimal.ZERO);
        goodsDTO.setGoodsGroupIds(dto.getGoodsGroupIds());
        goodsDTO.setHot(false);
        goodsDTO.setRecommend(false);
        goodsDTO.setNewGoods(false);
        goodsDTO.setImages(Arrays.asList(dto.getGoodsDetailResult().getCovers()));
        goodsDTO.setInitSaleNum(dto.getGoodsDetailResult().getSale());
        goodsDTO.setLimitBuyNum(0);
        goodsDTO.setVideoUrl("");
        goodsDTO.setSpuCode(dto.getGoodsDetailResult().getId().toString());
        goodsDTO.setSort(0);
        goodsDTO.setServicePackageArea(0);
        goodsDTO.setRemark("");
        goodsDTO.setOpenUserDiscount(false);
        goodsDTO.setMobileDetail("");
        goodsDTO.setThird(true);
        goodsDTO.setThirdSpuId(dto.getGoodsDetailResult().getId());
        goodsDTO.setSource(dto.getGoodsDetailResult().getSource());
        goodsDTO.setMobileDetail(dto.getGoodsDetailResult().getDescription());
        return goodsDTO;
    }


    private GoodsDTO mapToGoodsSkuList(GoodsDTO goodsDTO,PullChainGoodsDto pullChainGoodsDto)
    {
        List<GoodsSkuDTO> goodsSkuList = new ArrayList<>();
        List<SkuItem> allValues = goodsDTO.getValues();
        GoodsDetailResult.Option[] options = pullChainGoodsDto.getGoodsDetailResult().getSpecs().getOptions();
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();

        for(int i=0;i<options.length;i++)
        {
            GoodsSkuDTO goodsSkuDTO = new GoodsSkuDTO();
            GoodsDetailResult.Option option = options[i];
            if(CollectionUtil.isNotEmpty(stringIntegerHashMap) && stringIntegerHashMap.containsKey(option.getSpecValueIds()))
            {
                continue;
            }
            stringIntegerHashMap.put(option.getSpecValueIds(),1);
            String[] skuValueIds = option.getSpecValueIds().split("_");
            List<SkuSet> needValues = new ArrayList<>();
            for(int vi=0;vi<skuValueIds.length;vi++)
            {
                SkuItem skuItem = findSkuItem(allValues,skuValueIds[vi]);
                if(ObjectUtil.isNull(skuItem))
                {
                    throw new RRException("没有在第三方的商品规格值中找到对应的规格值");
                }
                SkuSet skuSet = new SkuSet();
                skuSet.setValue(skuItem);
                needValues.add(skuSet);
            }

            ProductSingleGoodsEntity singleGoodsEntity = syncCreateSingleGoods(goodsDTO, pullChainGoodsDto, option);


            goodsSkuDTO.setSkuSets(needValues);
            goodsSkuDTO.setExchangePoint(BigDecimal.ZERO);
            goodsSkuDTO.setSalePrice(MathUtils.setScale(option.getSalePrice()/100));
            goodsSkuDTO.setMarketPrice(MathUtils.setScale(option.getMarketPrice()/100));
            goodsSkuDTO.setWeight(MathUtils.setScale(option.getWeight()));
            goodsSkuDTO.setVolume(BigDecimal.ZERO);
            goodsSkuDTO.setSingleGoodsId(singleGoodsEntity.getId());
            goodsSkuDTO.setCover(option.getImage());
            goodsSkuDTO.setBarCode(option.getId().toString());
            goodsSkuDTO.setSingleGoodsTitle(singleGoodsEntity.getTitle());
            goodsSkuDTO.setSingleGoodsCode(singleGoodsEntity.getCode());
            goodsSkuDTO.setExchangePoint(BigDecimal.ZERO);

            goodsSkuDTO.setAgreementPrice(MathUtils.setScale(option.getAgreementPrice()/100));
            goodsSkuDTO.setThirdCostPrice(MathUtils.setScale(option.getCostPrice()/100));
            goodsSkuDTO.setGuidePrice(MathUtils.setScale(option.getGuidePrice()/100));
            goodsSkuDTO.setThirdSkuId(option.getId());
            goodsSkuList.add(goodsSkuDTO);
        }
        goodsDTO.setGoodsSkuList(goodsSkuList);
        return goodsDTO;
    }

    private ProductSingleGoodsEntity syncCreateSingleGoods(GoodsDTO goodsDTO, PullChainGoodsDto pullChainGoodsDto, GoodsDetailResult.Option option) {
        ProductSingleGoodsEntity load = productSingleGoodsService.loadByShopIdAndCount(goodsDTO.getShopId(),option.getId().toString());
        if(ObjectUtil.isNotEmpty(load))
        {
            load.setAbleStock(option.getStock());
            load.setCoverImage(option.getImage());
            load.setSku(option.getSpecValueNames());
            productSingleGoodsService.modify(load);
            return load;
        }
        else {
            ProductSingleGoodsEntity singleGoodsEntity = new ProductSingleGoodsEntity();
            singleGoodsEntity.setAdded(true);
            singleGoodsEntity.setShopId(goodsDTO.getShopId());
            singleGoodsEntity.setAbleStock(option.getStock());
            singleGoodsEntity.setCostPrice(MathUtils.setScale(option.getCostPrice() / 100));
            singleGoodsEntity.setCoverImage(option.getImage());
            singleGoodsEntity.setUnit(pullChainGoodsDto.getGoodsDetailResult().getUnit());
            singleGoodsEntity.setTitle(String.format("%s(%s)", goodsDTO.getTitle(), option.getSpecValueNames()));
            ProductGoodsGroupEntity goodsGroup = productGoodsGroupService.getByShopIdAndId(goodsDTO.getShopId(), goodsDTO.getGoodsGroupIds().get(0));
            singleGoodsEntity.setGoodsGroupId(goodsGroup.getId());
            singleGoodsEntity.setGoodsGroupName(goodsGroup.getName());
            singleGoodsEntity.setSku(option.getSpecValueNames());
            singleGoodsEntity.setOrderIndex(0);
            singleGoodsEntity.setCode(option.getId().toString());
            singleGoodsEntity = productSingleGoodsService.add(goodsDTO.getShopId(), singleGoodsEntity);
            return singleGoodsEntity;
        }
    }

    private SkuItem findSkuItem(List<SkuItem> allValues, String skuValueId) {
        for(SkuItem o : allValues)
        {
            if(o.getThirdId().equals(Long.valueOf(skuValueId)))
            {
                return o;
            }
        };
        return null;
    }


    private GoodsDTO mapToSkuTable(GoodsDTO goodsDTO,PullChainGoodsDto pullChainGoodsDto)
    {
        GoodsDetailResult.Specs specs = pullChainGoodsDto.getGoodsDetailResult().getSpecs();
        GoodsDetailResult.Name[] names = specs.getNames();
        GoodsDetailResult.Value[] values = specs.getValues();
        List<GoodsSkuTableItem> skuTableItems = new ArrayList<>();
        List<SkuItem> allValues = new ArrayList<>();
        for(int ni=0;ni<names.length;ni++)
        {
            GoodsSkuTableItem tableItem = new GoodsSkuTableItem();
            GoodsDetailResult.Name name = names[ni];
            SkuItem header =  skuService.getOrCreate(pullChainGoodsDto.getShopId(),name,0L);
            tableItem.setHead(header);
            List<SkuItem> skuItems = new ArrayList<>();
            for(int vi=0;vi<values.length;vi++)
            {

                if(!values[vi].getSpecNameId().equals(name.getId()))
                {
                    continue;
                }
                GoodsDetailResult.Value value = values[vi];
                SkuItem skuItem =  skuService.getOrCreate(pullChainGoodsDto.getShopId(),value,header.getId());
                skuItems.add(skuItem);
            }
            tableItem.setValues(skuItems);
            allValues.addAll(skuItems);
            skuTableItems.add(tableItem);
        }
        goodsDTO.setSkuTable(skuTableItems);
        goodsDTO.setValues(allValues);
        return goodsDTO;

    }

    /**
     * 商家查询自己家商品
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<Goods> page = this.page(
                new Query<Goods>().getPage(params),
                new QueryWrapper<Goods>()
        );
        return new PageUtils(page);
    }


    /**
     * 商家店铺中商品列表(包括代销的平台商品)
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryShopPage(Map<String, Object> params) {


        Long userId = MapUtil.getLong(params, "user_id");
        if (userId != null && userId > 0) {
            AccountEntity account = accountService.getUserById(userId, false);
            if (account != null) {
                params.put("subjection_shop_id", account.getSubjectionShopId());
            }

        }
        GoodsPageReq goodsPageReq = paramsMapToReq(params);
        goodsPageReq.setVerifyStatus(1);
        goodsPageReq.setAdded(1);


        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.queryShopPage(new Query<GoodsSlimVo>().getPage(params), goodsPageReq);
        return new PageUtils(goodsSlimVoIPage);
    }


    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 分页查询全平台商品
     * @param params 查询参数，包含以下几个参数：
     *               houniao_level1_category_id 候鸟的一级分类ID
     *               category_id 惠选系统的商品分类ID
     *               title 商品的关键字
     *               limit 分页查询时每页的最大记录数
     *               page 分页查询时的页码
     * @return 查询到的所有商品
     */
    @Override
    public PageUtils allPlatformPage(Map<String, Object> params) {

        // 取得候鸟category的id_path，并转换为惠选的categoryid
        String houniaoCategoryIdPath = String.valueOf(params.get("category_id_path"));
        if(StringUtils.isNotBlank(houniaoCategoryIdPath)) {
            Long huixuanCategoryId = GoodsCategoryConfig.getGoodsCategoryMap().get(houniaoCategoryIdPath);
            params.put("category_id", huixuanCategoryId);
        }

        String title = MapUtil.getStr(params, "title");
        Integer page = MapUtil.getInt(params, "page");
        page = page == null ? 1 : page;

        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.allPlatformPage(new Query<GoodsSlimVo>().getPage(params), paramsMapToReq(params));
        // 过滤掉售价为零和库存为零的商品
        if(goodsSlimVoIPage != null && goodsSlimVoIPage.getRecords() != null){
            List<GoodsSlimVo> goodsSlimVoList = goodsSlimVoIPage.getRecords();
            goodsSlimVoList = goodsSlimVoList.stream().filter(g -> {
                g.loadResidualInventory();
                return (g.getMinSalePrice().compareTo(BigDecimal.ZERO) > 0 && g.getResidualInventory() > 0);
            }).collect(Collectors.toList());
            goodsSlimVoIPage.setRecords(goodsSlimVoList);
        }

        try{
            //更新销量
            List<GoodsSlimVo> records = goodsSlimVoIPage.getRecords();
            //spu字符串
            String goodsSpu = "";
            for (GoodsSlimVo record : records) {
                goodsSpu = goodsSpu + goodsService.getById(record.getId()).getHouniaoSpuId() + ",";
            }
            goodsSpu = goodsSpu.substring(0, goodsSpu.length() - 1);
            JSONObject req = new JSONObject();
            req.put("goods_spu",goodsSpu);
            JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_GET_LIST.getUrl());
            JSONArray jsonArray = js.getJSONObject("data").getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                records.get(i).setResultSaleNum(Integer.valueOf(jsonArray.getJSONObject(i).get("sale_num").toString()));
            }
        }catch (Exception e){
            //注意只有search（通过搜索按钮触发才记录）
            if (StringUtils.isNotBlank(title) && page == 1) {
                if (goodsSlimVoIPage.getTotal() > 0) {
                    threadPoolExecutor.execute(() -> {
                        systemKeyWordSearchService.saveKeyWord(title);
                    });
                }
            }
            return new PageUtils(goodsSlimVoIPage);
        }
        //注意只有search（通过搜索按钮触发才记录）
        if (StringUtils.isNotBlank(title) && page == 1) {
            if (goodsSlimVoIPage.getTotal() > 0) {
                threadPoolExecutor.execute(() -> {
                    systemKeyWordSearchService.saveKeyWord(title);
                });
            }
        }
        return new PageUtils(goodsSlimVoIPage);
    }


    /**
     * 自营商品
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils querySelfPage(Map<String, Object> params) {
        GoodsPageReq goodsPageReq = paramsMapToReq(params);
        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.querySelfPage(new Query<GoodsSlimVo>().getPage(params), goodsPageReq);

        goodsSlimVoIPage.getRecords().forEach(o -> o.loadGroupSlimList(goodsPageReq.getShopId()));
        return new PageUtils(goodsSlimVoIPage);
    }

    /**
     * 平台查看所有商品为了审核
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryALLPage(Map<String, Object> params) {
        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.queryAllPage(new Query<GoodsSlimVo>().getPage(params), paramsMapToReq(params));
        return new PageUtils(goodsSlimVoIPage);
    }

    /**
     * 平台总店发布的商品
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPlatformPage(Map<String, Object> params) {

        ShopEntity platformShop = shopService.selectPlatformShop();
        params.put("platform_shop_id", platformShop.getId());
        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.queryPlatformPage(new Query<GoodsSlimVo>().getPage(params), paramsMapToReq(params));
        return new PageUtils(goodsSlimVoIPage);
    }

    /**
     * 普通商家代销的平台总店发布的商品
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryProxyPage(Map<String, Object> params) {
        ShopEntity platformShop = shopService.selectPlatformShop();
        params.put("platform_shop_id", platformShop.getId());
        GoodsPageReq goodsPageReq = paramsMapToReq(params);
        IPage<GoodsSlimVo> goodsSlimVoIPage = this.baseMapper.queryProxyPage(new Query<GoodsSlimVo>().getPage(params), goodsPageReq);
        for (GoodsSlimVo record : goodsSlimVoIPage.getRecords()) {
            record.loadGroupSlimList(goodsPageReq.getShopId());
        }
        return new PageUtils(goodsSlimVoIPage);
    }


    @Override
    public PageUtils querySelfForActivityPage(Map<String, Object> params) {
        params.put("added", 1);
        params.put("verify_status", 1);
        params.put("point_goods", 0);
        IPage<GoodsSlimVo> page = this.baseMapper.querySelfForActivityPage(new Query<GoodsSlimVo>().getPage(params), paramsMapToReq(params));
        return new PageUtils(page);
    }

    /**
     * 设置经营商品的店铺商品分组
     *
     * @param shopId
     * @param dto
     */
    @Override
    @Transactional
    public void setProxyGoodsGroup(Long shopId, SetGoodsGroupDTO dto) {
        shopService.loadShopBy(shopId, true);
        Goods goods = validateExists(dto.getGoodsId());
        GoodsAuthShop goodsAuthShop = goods.loadAuthByShop(shopId);
        if (goodsAuthShop == null) {
            throw new RRException(GoodsExceptionEnum.NOT_PROXY_AUTH);
        }

        setGoodsGroupRelation(shopId, goodsAuthShop.getId(), dto.getGoodsGroupIds());
    }


    private GoodsPageReq paramsMapToReq(Map<String, Object> params) {
        GoodsPageReq goodsPageReq = new GoodsPageReq();
        if (params.get("shop_id") != null) {
            goodsPageReq.setShopId(ClassConvertUtils.objToLong(params.get("shop_id").toString()));
        }
        if (params.get("shop_name") != null) {
            goodsPageReq.setShopName(params.get("shop_name").toString());
        }

        if (params.get("platform_shop_id") != null) {
            goodsPageReq.setPlatformShopId(ClassConvertUtils.objToLong(params.get("platform_shop_id").toString()));
        }

        if (params.get("subjection_shop_id") != null) {
            goodsPageReq.setSubjectionShopId(ClassConvertUtils.objToLong(params.get("subjection_shop_id").toString()));
        }

        if (params.get("client") != null) {
            goodsPageReq.setClient(params.get("client").toString());
        }

        if (params.get("title") != null) {
            goodsPageReq.setTitle(params.get("title").toString());
        }

        if (params.get("point_goods") != null) {
            goodsPageReq.setPointGoods(ClassConvertUtils.objToInteger(params.get("point_goods")));
        }
        else
        {
            goodsPageReq.setPointGoods(-1);
        }

        if (params.get("verify_status") != null) {
            goodsPageReq.setVerifyStatus(ClassConvertUtils.objToInteger(params.get("verify_status")));
        }

        if (params.get("added") != null) {
            goodsPageReq.setAdded(ClassConvertUtils.objToInteger(params.get("added")));
        }

        if (params.get("hot") != null) {
            goodsPageReq.setHot(ClassConvertUtils.objToInteger(params.get("hot")));
        }

        if (params.get("third") != null) {
            goodsPageReq.setThird(ClassConvertUtils.objToInteger(params.get("third")));
        }

        if (params.get("order_type") != null) {
            goodsPageReq.setOrderType(ClassConvertUtils.objToInteger(params.get("order_type")));
        }

        if (params.get("order_mode") != null) {
            goodsPageReq.setOrderMode(params.get("order_mode").toString());
        }

        if (params.get("area_feature") != null) {
            goodsPageReq.setAreaFeature(MapUtil.getInt(params,"area_feature"));
        }
        else
        {
            goodsPageReq.setAreaFeature(-1);
        }

        if (params.get("type") != null) {
            goodsPageReq.setType(params.get("type").toString());
        }

        if (params.get("limit") != null) {
            goodsPageReq.setLimit(ClassConvertUtils.objToInteger(params.get("limit")));
        }

        if (params.get("seckill_id") != null) {
            goodsPageReq.setSeckillId(ClassConvertUtils.objToLong(params.get("seckill_id").toString()));
        }

        if (params.get("hx_category_id") != null) {
            goodsPageReq.setHxCategoryId(ClassConvertUtils.objToLong(params.get("hx_category_id").toString()));
        }

        if (params.get("group_buy_id") != null) {
            goodsPageReq.setGroupBuyId(ClassConvertUtils.objToLong(params.get("group_buy_id").toString()));
        }

        if (params.get("week") != null) {
            DateTime dateTime = DateUtil.beginOfWeek(new Date());
            goodsPageReq.setAddedStartTime(dateTime);
        }
        String keywords = MapUtil.getStr(params, "keywords");
        if (StringUtils.isNotBlank(keywords)) {
            String[] keywordArr = StringUtils.split(keywords, ',');
            goodsPageReq.setKeywordArr(Arrays.asList(keywordArr));

        }

        if (params.get("group_id") != null) {
            goodsPageReq.setGroupId(ClassConvertUtils.objToLong(params.get("group_id")));
            List<ProductGoodsGroupEntity> children = productGoodsGroupService.getChildren(goodsPageReq.getGroupId());
            List<Long> collect = children.stream().map(ProductGoodsGroupEntity::getId).collect(Collectors.toList());
            if (collect.size() > 0) {
                goodsPageReq.setChildrenIds(collect);
            }

        }


        if (params.get("category_id") != null) {
            Long categoryId = ClassConvertUtils.objToLong(params.get("category_id"));
            goodsPageReq.setCategoryId(categoryId);
            List<SystemProductCategoryEntity> children = systemProductCategoryService.getChildren(categoryId);
            List<Long> collect = children.stream().map(SystemProductCategoryEntity::getId).collect(Collectors.toList());
            if (collect.size() > 0) {
                collect.add(categoryId);
                goodsPageReq.setChildrenCategoryIds(collect);
            }

        }

        if (params.get("houniao_level1_category_id") != null) {
            String houniaoLevel1CategoryId = String.valueOf(params.get("houniao_level1_category_id"));
            if(StringUtils.isNotBlank(houniaoLevel1CategoryId)){
                Set<Long> categoryIdSet = new HashSet<>();
                GoodsCategoryConfig.getGoodsCategoryMap().forEach((k, v) -> {
                    if(k.startsWith(String.valueOf(houniaoLevel1CategoryId) + "_") && !categoryIdSet.contains(v)){
                        categoryIdSet.add(v);
                    }
                });
                goodsPageReq.setChildrenCategoryIds(categoryIdSet.stream().collect(Collectors.toList()));
            }
        }

        return goodsPageReq;

    }


    @Override
    public Goods getByShopIdAndId(Long shopId, Long id) {
        Goods goods = this.getOne(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getShopId, shopId)
                .eq(Goods::getId, id)
                .last("limit 1"));
        if (goods == null) {
            throw new RRException(GoodsExceptionEnum.GOODS_NOT_EXISTS);
        }

        return goods;
    }

    @Override
    public Goods getById(Long id, boolean tw) {
        Goods goods = this.getById(id);
        if (goods == null && tw) {
            throw new RRException(GoodsExceptionEnum.GOODS_NOT_EXISTS);
        }
        if (goods.getThird()){
            JSONObject req = new JSONObject();
            req.put("goods_spu",goods.getSpuCode());
            JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_GET_INFO.getUrl());
            //获取数据
            JSONObject data = js.getJSONObject("data");

            JSONObject jsonObject = data;
            //Goods goods = new Goods();
            //shopId 30为候鸟
            goods.setShopId(35L);
            goods.setRealSaleNum(Integer.valueOf(jsonObject.get("sale_num").toString()));
            goods.setResultSaleNum(Integer.valueOf(jsonObject.get("sale_num").toString()));
            goods.setCover(jsonObject.getJSONObject("goods_img").get("img").toString());
            //分类id TODO: 存商品前，分好商品类  根据商品的spu去商品详情查
            //获取category_id_path 做判断
            String category_id_path = jsonObject.get("category_id_path").toString();
            //获取category_id_path的前两位
            category_id_path = category_id_path.substring(0,category_id_path.lastIndexOf("_"));
            //分类
            // Long categoryId = getCategoryId(category_id_path);
            Long categoryId = GoodsCategoryConfig.getGoodsCategoryMap().get(category_id_path);
            goods.setCategoryId(categoryId);

            /**
             * 商品价格倍率
             */
            //商品价格
            BigDecimal min_price = new BigDecimal(data.get("min_price").toString());
            //候鸟商品价格倍率
            BigDecimal priceMultiplier = new BigDecimal(goodsPriceMultiplier);
            //最终价格
            BigDecimal result = min_price.multiply(priceMultiplier);
            goods.setMinSalePrice(result);
            goods.setMaxSalePrice(result);
            goods.setMinMarketPrice(result);
            goods.setMaxMarketPrice(result);

            goods.setMinExchangePoint(new BigDecimal(0.00));
            goods.setTitle(jsonObject.get("goods_name").toString());
            goods.setVideoUrl("");
            goods.setShortTitle("");
            goods.setSpuCode(jsonObject.get("goods_spu").toString());
            //商品规格 添加商品时设置为null  添加商品规格时 更新字段
            goods.setGoodsSkuList(new ArrayList<>());
            goods.setInitSaleNum(0);
            goods.setLimitBuyNum(0);
            //实际出售量
            goods.setRealSaleNum(Integer.valueOf(jsonObject.get("sale_num").toString()));
            //是否是积分兑换
            goods.setPointGoods(false);
            //浏览量
            goods.setPv(0L);
            goods.setVerifyStatus(GoodsConstant.VerifyStatus.YES);
            //顺序暂时为0 不知道干什么用的
            goods.setSort(Integer.valueOf(0));
            //是否是平台商品  暂时设置为不是
            goods.setPlatformStore(false);
            //运费模版 暂时写死
            goods.setFreightTemplateId(6);
            //最后审核时间  暂时设置为导入时间
            goods.setLastVerifyTime(new Date());
            //软删除  0正常 -1删除
            goods.setDeleted(0);
            //是否开启会员折扣  暂时为false 不知道具体用途
            goods.setOpenUserDiscount(false);
            //暂时设置为热销
//            goods.setHot(false);
            //是否是新品  暂时设置为不是
//            goods.setNewGoods(false);
            //是否推荐 暂时设置为是
            goods.setRecommend(false);
            goods.setAverage(new BigDecimal(5.0));
            //是否可以代理销售暂时设置为false
            goods.setAbleProxySale(false);
            goods.setGiftType(GoodsConstant.GiftType.NO);
            //赠送积分先设置为0
            goods.setGivePoint(new  BigDecimal(0));
            //赠送消费值 暂时写死 不知道计算原理
            goods.setConsumptionValue(goods.getMinSalePrice());
            goods.setFree(false);
            //是否是激活商品  暂时设置为是
            goods.setAreaFeature(GoodsConstant.AreaFeature.GENERAL);
            //三方的spuid暂时写死
            goods.setHouniaoSpuId(goods.getSpuCode());
            //是否是三方产品 暂时设置为是
            goods.setThird(true);
            //sorce  暂时给99
            goods.setSource(99);
            //规格
            goods.setSkuTable(new ArrayList());
            //TODO:商品更新
//            goodsService.updateBatchById(goods);

            // 详情图片
//            JSONObject xiangqing = new JSONObject();
//            xiangqing.put("goods_spu", goods.getSpuCode());
//            JSONObject xiangqingjs = houniaoApiUtil.client(xiangqing, HouniaoConstant.GOODS_GET_INFO.getUrl());
            JSONObject xiangqingjs = js;
            // 遍历返回的"goods_desc_image"
            JSONObject data2 = xiangqingjs.getJSONObject("data");
            JSONArray goods_desc_image = data2.getJSONArray("goods_desc_image");
            StringBuilder goods_desc_image_url = new StringBuilder();
            String qian = "<img src=\"";
            // 遍历图片
            goods_desc_image.forEach(item -> {
                goods_desc_image_url.append(qian);
                goods_desc_image_url.append(item.toString());
                goods_desc_image_url.append("\">");
            });
            // StringBuilder -> String
            String goods_desc_image_urls = goods_desc_image_url.toString();
            String zuizhong = "<p>" + goods_desc_image_urls + "</p>";
            goodsContentService.setGoodsContent(goods.getId(), zuizhong);
            //商家的单品表，用来管理库存  //TODO:库存批量导入
            ProductSingleGoodsEntity ps = productSingleGoodsService.getOne(new LambdaQueryWrapper<ProductSingleGoodsEntity>()
                    .eq(ProductSingleGoodsEntity::getCode, goods.getSpuCode())
                    .last("LIMIT 1")
            );
//            ProductSingleGoodsEntity ps = new ProductSingleGoodsEntity();
            ps.setGoodsGroupId(69L);
            ps.setGoodsGroupName("999");
            ps.setCode(goods.getSpuCode());
            ps.setTitle(goods.getTitle());
            ps.setCoverImage(goods.getCover());
            ps.setUnit(data2.get("unit_name").toString());
            ps.setCostPrice(goods.getMinSalePrice());
            ps.setOrderIndex(0);
            ps.setDeleted(0);
            ps.setShopId(35L);
            ps.setSku(data2.get("unit_name").toString());
            ps.setAdded(true);
            //productSingleGoodsService.add(ps.getShopId(),ps);
            //获取商品规格
            JSONObject req1 = new JSONObject();
            req1.put("goods_spu",goods.getSpuCode());
            JSONObject json = houniaoApiUtil.client(req1, HouniaoConstant.GOODS_GET_GOODS_SPEC_PRICE_BATCH.getUrl());
            JSONArray data3 = json.getJSONArray("data");
            JSONObject jsonObject1 = data3.getJSONObject(0);
            JSONArray sku_list = jsonObject1.getJSONArray("sku_list");

            // 准备一个goods表的拼接字符串
            StringBuilder sb = new StringBuilder();
            int size = sku_list.size();
            //商品库存数
            int num = 0;
            //规格集合
            List<GoodsSku> skuList = new ArrayList<>();
            for (int j = 0;j < size; j++){
                JSONObject jsonObject2 = JSON.parseObject(JSONObject.toJSONString(sku_list.get(j)));
                String sku_name = jsonObject2.getString("sku_name");
                GoodsSku goodsSku = goodsSkuService.getOne(new LambdaQueryWrapper<GoodsSku>()
                        .eq(GoodsSku::getGoodsId, goods.getId())
                        .eq(GoodsSku::getThirdSkuId, Long.valueOf(sku_list.getJSONObject(j).get("sku_id").toString()))
                );
                if (goodsSku == null){
                    continue;
                }
                // skus表新增
                ProductSkusEntity skusEntity = productSkusService.getById(goodsSku.getSkuHashCode());
                //规格数量
                num += Integer.valueOf(sku_list.getJSONObject(j).get("sku_stock").toString());
//                ProductSkusEntity skusEntity = new ProductSkusEntity();
                skusEntity.setName(sku_name);
                skusEntity.setShopId(35L);
                skusEntity.setParentSkuId(53L);
                skusEntity.setOrderIndex(1);
                productSkusService.updateById(skusEntity);
                Long skusEntity_id = skusEntity.getId();
                // sku_relation表新增
                //商品的规格的关系表（一个商品可能会有多个规格，各个规格中要关联单品） TODO:规格数据更新
//                GoodsSku goodsSku = new GoodsSku();
                goodsSku.setGoodsId(goods.getId());
                //单品id  不知道怎么用  暂时设置为sku_id  TODO:SingleGoodsId 设为 goodsId
                goodsSku.setSingleGoodsId(ps.getId());

                /**
                 * 候鸟商品倍率
                 */
                BigDecimal skuPrice = new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString());
                BigDecimal skuPriceResult = skuPrice.multiply(new BigDecimal(goodsPriceMultiplier));

                if (j == 0){
                    goods.setMinSalePrice(skuPriceResult);
                    goods.setConsumptionValue(skuPriceResult);
                    goods.setMaxMarketPrice(skuPriceResult);
                }
                //实际售价暂时设置为规格价格
                goodsSku.setSalePrice(skuPriceResult);
                //划线价格暂时设置为规格价格
                goodsSku.setMarketPrice(skuPriceResult);


                goodsSku.setWeight(new BigDecimal(sku_list.getJSONObject(j).get("sku_weight").toString()));
                //体积暂时设为0
                goodsSku.setVolume(new BigDecimal(0));
                //规格组合配置的字符串设置 TODO:删除了setSkuSetValue中的方法需要修改
                String str ="[{\"value\": {\"name\": \"" + sku_name + "\",\"id\": \"" + skusEntity_id + "\"}}]";
                String str1 ="{\"name\":\"" + sku_name + "\",\"id\":\"" + skusEntity_id + "\"}";
                goodsSku.setSkuSetValue(str);
                //商品规格编码
                goodsSku.setBarCode(sku_list.getJSONObject(j).get("spec_sku").toString());
                //兑换积分暂时设置为0
                goodsSku.setExchangePoint(new BigDecimal(0));
                goodsSku.setCover(sku_list.getJSONObject(j).get("spec_img").toString());
                goodsSku.setSkuSetName(sku_list.getJSONObject(j).getJSONArray("sku_attribute_name").get(0).toString());
                //单品码 暂时设置为spu编码
                goodsSku.setSingleGoodsCode(goods.getSpuCode());
                //单品标题
                goodsSku.setSingleGoodsTitle(goods.getTitle());
                //skuHashCode连接规格表用的
                goodsSku.setSkuHashCode(skusEntity_id.toString());
                goodsSku.setShopId(goods.getShopId());
                goodsSku.setThirdSkuId(Long.valueOf(sku_list.getJSONObject(j).get("sku_id").toString()));
                goodsSku.setAgreementPrice(new BigDecimal(0.00));
                //三方成本价 写死
                goodsSku.setThirdCostPrice(goodsSku.getSalePrice());
                //指导价 写死
                goodsSku.setGuidePrice(goodsSku.getSalePrice());
                skuList.add(goodsSku);
                // 拼接goods表要的字符串
                sb.append(str1 + ",");
            }
            //TODO:商品更新
//            goodsSkuService.branchCreate(goods.getId(),skuList);
            if (skuList.size() > 0){
                goodsSkuService.updateBatchById(skuList);
            }
            // 最后给goods表的sku_table_value字段拼接好 head块
            // StringBuilder -> String 并且去除最后的逗号
            if (sb.length() > 0){
                String string = sb.substring(0, sb.length() - 1);
                String str1 = "[{\"values\":"+ "[" + string +"],\"head\":{\"name\":\"产品\",\"id\":53}}]";
                goods.setSkuTableValue(str1);
            }
            // 商品表img_value
            JSONObject goods_img = data2.getJSONObject("goods_img");
            String img = goods_img.get("img").toString();
            String imgValue = "[\"" + img + "\"]";
            goods.setImagesValue(imgValue);
            goods.setGoodsSkuList(skuList);
            goodsService.updateById(goods);
            //为了实时更新库存
            ps.setAbleStock(num);
            productSingleGoodsService.update(ps.getShopId(),ps);
//        }
            return goods;
        }
        return goods;
    }


    /**
     * 获得当前用户，在当前商品中的折扣（直接给从商品详情页）
     *
     * @param userId
     * @param goods
     * @return
     */
    @Override
    public BigDecimal getUserGoodsDiscount(Long userId, Goods goods) {
        if (goods == null || userId.equals(0)) {
            return new BigDecimal("10");
        }

        if (!goods.getOpenUserDiscount()) {
            return new BigDecimal("10");
        }
        GoodsUserDiscountConfig goodsUserDiscountConfig = goods.loadGoodsUserDiscountConfig();
        //确认是用那家店铺来获取会员的等级
        Long realShopId = goods.getShopId();
        //获取会员的等级
        UserShopRoleEntity userShopRole = userShopRoleService.getUserShopRole(realShopId, userId);
        if (userShopRole == null) {
            return new BigDecimal("10");
        }

        //如果没有设置商品会员等级折扣，起用店铺级的等级
        if (goodsUserDiscountConfig == null || goodsUserDiscountConfig.getUseDefault()) {
            ShopUserRoleConfigEntity role = shopUserRoleConfigService.getByShopIdAndRoleCode(realShopId, userShopRole.getRoleCode());
            if (role == null) {
                return new BigDecimal("10");
            }
            return role.getDiscount();
        } else {
            //如果有商品会员等级折扣
            List<GoodsUserDiscountDetail> details = goodsUserDiscountConfig.getDetails();
            if (details.size() == 0) {
                return new BigDecimal("10");
            }
            Optional<GoodsUserDiscountDetail> first = details.stream().filter(o -> o.getRoleCode().equals(userShopRole.getRoleCode())).findFirst();
            if (!first.isPresent()) {
                return new BigDecimal("10");
            }
            return first.get().getDiscount();
        }
    }


    /**
     * 发布商品
     *
     * @param shopId
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Goods add(Long shopId, GoodsDTO dto) {
        ShopEntity shop = shopService.loadShopBy(shopId, true);
        validateProductCategoryExists(dto.getCategoryId());
        validateHxCategoryExists(dto.getHxCategoryId());
        Goods entity = new Goods();
        entity.setIsOfflineProduct(dto.getIsOfflineProduct());
        BeanUtils.copyProperties(dto, entity);
        entity.setShopId(shopId);

        //将DTO中的商品规格数据映射成商品规格模型数据
        List<GoodsSku> goodsSkuList = this.goodsSkuDTOsMapGoodsSkuList(shopId, dto);
        //通过规格处理价格方面的容余字段
        entity.handelGoodsSkuList(goodsSkuList);
        entity.computeResultSaleNum();
        entity.setPlatformStore(shop.getPlatformShop());
        setGoodsFreightTemplate(entity);

        if(entity.getPointGoods())
        {
            entity.setFree(false);
            entity.setAreaFeature(GoodsConstant.AreaFeature.GENERAL);
        }
        else
        {
            entity.setAreaFeature(GoodsConstant.AreaFeature.getByCode(dto.getAreaFeature()));
        }

        entity = this.create(entity);

        //创建商品与自己店铺的授权信息
        GoodsAuthShop auth = goodsAuthShopService.add(shopId, entity);

        //创建商品与分组关系
        if(dto.getGoodsGroupIds()!=null && dto.getGoodsGroupIds().size()>0) {
            setGoodsGroupRelation(shopId, auth.getId(), dto.getGoodsGroupIds());
        }

        //创建商品skus
        goodsSkuService.branchCreate(entity.getId(), goodsSkuList);

        //创建商品的详情
        goodsContentService.setGoodsContent(entity.getId(), dto.getMobileDetail());

        return entity;
    }

    private void validateHxCategoryExists(Long hxCategoryId) {
        if(ObjectUtil.isNotNull(hxCategoryId) ) {
            HxCategoryEntity entity = hxCategoryEntityService.getById(hxCategoryId);
            if (entity == null) {
                throw new RRException(GoodsExceptionEnum.CATEGORY_NOT_EXISTS);
            }
        }
    }


    private void setGoodsFreightTemplate(Goods goods) {
        FreightTemplate fTemplate = freightTemplateService.getFTemplateBy(goods.getShopId(), goods.getFreightTemplateId());
        if (fTemplate == null) {
            fTemplate = freightTemplateService.getFTemplateDefaultBy(goods.getShopId());
            if (fTemplate == null) {
                throw new RRException(GoodsExceptionEnum.FREIGHT_TEMPLATE_NOT_EXISTS);
            }
            goods.setFreightTemplateId(fTemplate.getId());
        }
    }

    /**
     * 修改商品
     *
     * @param shopId
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Goods update(Long shopId, GoodsDTO dto) {
        shopService.loadShopBy(shopId, true);
        Goods entity = validateExists(dto.getId());
        validateProductCategoryExists(dto.getCategoryId());
        validateHxCategoryExists(dto.getHxCategoryId());
        validateGoodsShopSafe(shopId, entity);


        BeanUtils.copyProperties(dto, entity);
        entity.setShopId(shopId);
        setGoodsFreightTemplate(entity);
        //将DTO中的商品规格数据映射成商品规格模型数据
        List<GoodsSku> goodsSkuList = this.goodsSkuDTOsMapGoodsSkuList(shopId, dto);
        //通过规格处理价格方面的容余字段
        entity.handelGoodsSkuList(goodsSkuList);
        entity.computeResultSaleNum();
        entity.setVerifyStatus(GoodsConstant.VerifyStatus.WAIT);

        if(entity.getPointGoods())
        {
            entity.setFree(false);
            entity.setAreaFeature(GoodsConstant.AreaFeature.GENERAL);
        }
        else
        {
            entity.setAreaFeature(GoodsConstant.AreaFeature.getByCode(dto.getAreaFeature()));
        }

        this.modify(entity);


        //创建商品与分组关系
        if(dto.getGoodsGroupIds()!=null && dto.getGoodsGroupIds().size()>0) {
            setGoodsGroupRelation(shopId, entity.loadPublishAuth().getId(), dto.getGoodsGroupIds());
        }


        //创建商品skus
        goodsSkuService.branchCreate(entity.getId(), goodsSkuList);
        //创建商品的详情
        goodsContentService.setGoodsContent(entity.getId(), dto.getMobileDetail());
        return entity;
    }

    /**
     * 审核商品
     *
     * @param goodsId
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public void check(Long goodsId, GoodsStatusDTO dto) {
        Goods entity = this.validateExists(goodsId);
        entity.setVerifyStatus(GoodsConstant.VerifyStatus.getByCode(dto.getVerifyStatus()));
        entity.setLastVerifyTime(new Date());
        entity.setVerifyRemark(dto.getRemark());
        this.updateById(entity);

        /**
         * 如果发现问题商品，审核不通过，下架所有经营权限
         * 如果审核的是加盟商的商品这里还好，只会下架加盟商的自营商品
         * 如果审核的是平台商品，一旦需要下架所有代销商的商品，只要审核不通过平台的商品就可以
         */
        if (GoodsConstant.VerifyStatus.NO.equals(dto.getVerifyStatus())) {
            dto.setAdded(false);
            goodsAuthShopService.added(entity.getShopId(), dto);
        }
    }

    /**
     * 上架下架
     *
     * @param shopId
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public void added(Long shopId, GoodsStatusDTO dto) {
        shopService.loadShopBy(shopId, true);
        goodsAuthShopService.added(shopId, dto);
    }

    /**
     * 设置热销
     *
     * @param shopId
     * @param dto
     */
    @Override
    public void hot(Long shopId, GoodsStatusDTO dto) {

        Goods goods = this.getByShopIdAndId(shopId, dto.getGoodsId());
        goods.setHot(dto.getHot());
        this.modify(goods);
    }

    @Override
    public void hot(Long goodsId) {
        Goods goods = this.getById(goodsId);
        goods.setHot(goods.getHot() == true ? false : true);
//        goods.setHot(!goods.getHot());
        this.modify(goods);
    }

    /**
     * 设置新品
     *
     * @param shopId
     * @param dto
     */
    @Override
    public void newGoods(Long shopId, GoodsStatusDTO dto) {
        Goods goods = this.getByShopIdAndId(shopId, dto.getGoodsId());
        goods.setNewGoods(dto.getNewGoods());
        this.modify(goods);
    }

    /**
     * 设置成推荐
     *
     * @param shopId
     * @param dto
     */
    @Override
    public void recommend(Long shopId, GoodsStatusDTO dto) {
        Goods goods = this.getByShopIdAndId(shopId, dto.getGoodsId());
        goods.setRecommend(dto.getRecommend());
        this.modify(goods);
    }

    /**
     * 代销平台商品
     *
     * @param shopId
     * @param goodsId
     */
    @Override
    public void auth(Long shopId, Long goodsId) {
        shopService.loadShopBy(shopId, true);
        Goods goods = this.getById(goodsId);
        if (!goods.getPlatformStore()) {
            //只有平台商品才可以代销
            throw new RRException(GoodsExceptionEnum.PLATFORM_GOODS_AUTH);
        }
        goodsAuthShopService.auth(shopId, goodsId);
    }


    /**
     * 取消商品的某个店铺的经营权限
     *
     * @param shopId
     * @param goodsId
     */
    @Override
    @Transactional
    public void cancelAuth(Long shopId, Long goodsId) {
        shopService.loadShopBy(shopId, true);
        goodsAuthShopService.cancelAuth(shopId, goodsId);
    }


    /**
     * 验证商品分组是否存在
     *
     * @param id
     */
    private Goods validateExists(Long id) {
        Goods entity = this.baseMapper.selectById(id);
        if (entity == null) {
            throw new RRException(GoodsExceptionEnum.GOODS_NOT_EXISTS);
        }

        return entity;
    }

    /**
     * 只能操作自己店铺的商品
     */
    private void validateGoodsShopSafe(Long shopId, Goods goods) {
        if (goods.getShopId() != shopId) {
            throw new RRException(GoodsExceptionEnum.GOODS_SHOP_SAFE);
        }

    }

    /**
     * 将DTO中的商品规格数据映射成商品规格模型数据
     *
     * @param dto
     * @return
     */
    private List<GoodsSku> goodsSkuDTOsMapGoodsSkuList(Long shopId, GoodsDTO dto) {
        if (dto.getGoodsSkuList().size() == 0) {
            throw new RRException(GoodsExceptionEnum.NEED_GOODS_SKU);
        }

        List<GoodsSku> relations = new ArrayList<>();
        dto.getGoodsSkuList().forEach(skuDTO -> {
            ProductSingleGoodsEntity productSingleGoodsEntity = getProductSingleGoodsEntity(shopId, skuDTO.getSingleGoodsId());
            skuDTO.setSingleGoodsCode(productSingleGoodsEntity.getCode());
            skuDTO.setSingleGoodsTitle(productSingleGoodsEntity.getTitle());
            if(dto.getFree())
            {
                skuDTO.setSalePrice(BigDecimal.ZERO);
                skuDTO.setExchangePoint(BigDecimal.ZERO);
            }
            GoodsSku sku = new GoodsSku();
            //BeanUtils.copyProperties(skuDTO, sku);
            BeanUtil.copyPropertiesIgnoreNull(skuDTO, sku);
            sku.setShopId(shopId);
            relations.add(sku);
        });
        return relations;

    }

    private ProductSingleGoodsEntity getProductSingleGoodsEntity(Long shopId, Long singleGoodsId) {
        ProductSingleGoodsEntity entity = singleGoodsService.getByShopIdAndId(shopId, singleGoodsId);
        if (entity == null) {
            throw new RRException(GoodsExceptionEnum.SINGLE_GOODS_NOT_EXISTS);
        }
        return entity;
    }

    /**
     * 创建商品经营权限与分组关系
     *
     * @param shopId
     * @param authId
     * @param groupIds
     */
    private void setGoodsGroupRelation(Long shopId, Long authId, List<Long> groupIds) {
        shopService.loadShopBy(shopId, true);
        if (groupIds == null || groupIds.size() == 0) {
            throw new RRException(GoodsExceptionEnum.NEED_GOODS_GROUP);
        }
        List<GoodsGroupRelation> relations = new ArrayList<>();
        groupIds.forEach(groupId -> {
            GoodsGroupRelation relation = new GoodsGroupRelation();
            relation.setGoodsAuthShopId(authId);
            ProductGoodsGroupEntity group = productGoodsGroupService.getByShopIdAndId(shopId, groupId);
            if (group == null) {
                throw new RRException(GoodsExceptionEnum.PRODUCT_GROUP_NOT_EXISTS);
            }
//            if (group.getParentId() == 0) {
//                throw new RRException(GoodsExceptionEnum.PRODUCT_GROUP_SELECT_SECOND);
//            }

            relation.setGoodsGroupId(groupId);
            relations.add(relation);
        });

        goodsGroupRelationService.branchCreate(authId, relations);
    }


    public void validateProductCategoryExists(Long categoryId) {
        if(categoryId > 0 ) {
            Map<String, Long> goodsCategoryMap = GoodsCategoryConfig.getGoodsCategoryMap();
            Set<String> keys = goodsCategoryMap.keySet();
            for (String key : keys){
                int index = key.indexOf("_") + 1;
                String key1 = key.substring(index);
                if(String.valueOf(categoryId).equals(key1)){
                    Long aLong = goodsCategoryMap.get(key);
                    categoryId = aLong;
                    break;
                }
            }
            SystemProductCategoryEntity entity = SystemProductCategoryService.getById(categoryId);
            if (entity == null) {
                throw new RRException(GoodsExceptionEnum.CATEGORY_NOT_EXISTS);
            }
        }
    }

}
